//
//  UIImagePickerController+rx.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/22.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa


extension Reactive where Base: UIImagePickerController {
    
    var imagePickerDelegate: RxImagePickerDelegateProxy {
        return RxImagePickerDelegateProxy.proxy(for: base)
    }

    var didFinishPickingMediaWithInfo: Observable<[UIImagePickerController.InfoKey : Any]> {
        return imagePickerDelegate
            .methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerController(_:didFinishPickingMediaWithInfo:)))
            .map {
                guard let info = $0[1] as? [UIImagePickerController.InfoKey : Any] else { fatalError() }
                return info
            }
    }
    
    var didCancel: Observable<()> {
        return imagePickerDelegate
            .methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerControllerDidCancel(_:)))
            .map {_ in () }
    }
    
    static func create(_ parent: UIViewController,
                       animated: Bool = true,
                       config: @escaping (UIImagePickerController) throws -> Void = { _ in })
        -> Observable<UIImagePickerController> {
        return .create({ [weak parent] (observer) -> Disposable in
            let imagePicker = UIImagePickerController()
            let cancelDispose = imagePicker.rx.didCancel
                .subscribe(onNext: { [weak imagePicker] in
                    imagePicker?.safeDismiss()
                })
            
            do {
                try config(imagePicker)
            } catch {
                observer.onError(error)
                return Disposables.create()
            }
            
            guard let parent = parent else {
                observer.onCompleted()
                return Disposables.create()
            }
            
            parent.present(imagePicker, animated: animated)
            observer.onNext(imagePicker)
            
            return Disposables.create(cancelDispose, Disposables.create { [weak imagePicker] in
                imagePicker?.safeDismiss()
            })
        })
    }
    
}
